<template>
  <div class="container">
    <a-card>
      <a-row style="margin-bottom: 16px">
        <a-col :span="16">
          <a-space>
            <a-button
              v-permission="authority.SYS_ROLE_ADD"
              type="primary"
              @click="add"
            >
              <template #icon>
                <icon-plus />
              </template>
              新建
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-table
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        :data="renderData"
        :columns="columns"
        :bordered="{ wrapper: true, cell: true }"
        @page-change="changeCurrent"
        @page-size-change="changePageSize"
      >
        <template #operations="{ record }">
          <a-button
            v-permission="authority.SYS_ROLE_PERM"
            type="text"
            size="small"
            @click="perm(record.id)"
          >
            <template #icon>
              <icon-tool />
            </template>
            权限
          </a-button>
          <a-button
            v-permission="authority.SYS_ROLE_EDIT"
            type="text"
            size="small"
            @click="edit(record)"
          >
            <template #icon>
              <icon-edit />
            </template>
            编辑
          </a-button>
          <a-popconfirm
            :content="`此操作将永久删除该角色(${record.roleName}), 是否继续?`"
            type="warning"
            @ok="del(record.id)"
          >
            <a-button
              v-permission="authority.SYS_ROLE_DEL"
              type="text"
              size="small"
              status="danger"
            >
              <template #icon>
                <icon-delete />
              </template>
              删除
            </a-button>
          </a-popconfirm>
        </template>
      </a-table>
    </a-card>
    <RoleForm
      v-model:visible="formDialogVisible"
      :form-data="formData"
      @refresh="refresh"
    />
    <div>
      <a-modal
        :visible="permModalVisible"
        title="分配权限"
        width="400px"
        @ok="handleOk"
        @cancel="handleCancel"
      >
        <a-tree
          ref="treeRef"
          v-model:checked-keys="checkedKeys"
          :data="treeData"
          :checkable="true"
          :check-strictly="true"
          :virtual-list-props="{
            height: 500,
          }"
        />
      </a-modal>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { usePagination, useRequest } from 'vue-request';
  import authority from '@/utils/authority';
  import defaultPageOptions from '@/utils/pagination';
  import {
    getRolePage,
    deleteRole,
    DATA_SCOPES,
    updatePermission,
  } from '@/api/upms/role';
  import { getAllMenuList, getRoleMenuIds } from '@/api/upms/menu';
  import { assembleTree } from '@/utils/util';
  import RoleForm from './components/role-form.vue';

  const {
    data,
    loading,
    changeCurrent,
    changePageSize,
    refresh,
    current,
    pageSize,
    total,
  } = usePagination(getRolePage, { ...defaultPageOptions });

  const renderData = computed(() => data.value?.records || []);

  const formData = ref();

  const pagination = computed(() => ({
    current: current.value,
    pageSize: pageSize.value,
    showTotal: true,
    showPageSize: true,
    total: total.value,
  }));

  const columns = [
    { title: 'ID', dataIndex: 'id' },
    { title: '角色名称', dataIndex: 'roleName' },
    { title: '角色编码', dataIndex: 'roleCode' },
    { title: '角色描述', dataIndex: 'roleDesc' },
    {
      title: '数据权限',
      dataIndex: 'dsType',
      render: ({ record }: { record: any }) =>
        DATA_SCOPES.find((scope) => scope.value === record.dsType)?.label,
    },
    { title: '操作', slotName: 'operations' },
  ];

  // 弹出框标记
  const formDialogVisible = ref(false);

  const permModalVisible = ref(false);

  const { data: treeData } = useRequest(async () =>
    assembleTree(await getAllMenuList())
  );

  const add = () => {
    formData.value = {};
    formDialogVisible.value = true;
  };
  const edit = (e: any) => {
    formDialogVisible.value = true;
    formData.value = { ...e };
  };
  const del = async (id: string) => {
    await deleteRole(id).then(() => {
      Message.success('删除成功');
      refresh();
    });
  };

  const checkedKeys = ref<string[]>([]);

  const treeRef = ref();

  const roleId = ref<string>('');

  const { runAsync } = useRequest((id) => getRoleMenuIds(id), {
    manual: true,
  });

  const perm = async (id: string) => {
    roleId.value = id;
    const menuIds = await runAsync(id);
    checkedKeys.value = menuIds;
    permModalVisible.value = true;
  };

  const handleOk = () => {
    if (checkedKeys.value?.length > 0) {
      updatePermission({
        roleId: roleId.value,
        menuId: checkedKeys.value.join(','),
      }).then(() => {
        Message.success('分配成功');
        permModalVisible.value = false;
      });
    } else {
      Message.error('请选择权限');
    }
  };
  const handleCancel = () => {
    permModalVisible.value = false;
  };
</script>

<script lang="ts">
  export default {
    name: 'Role',
  };
</script>

<style scoped lang="less">
  .container {
    padding: 0px 10px 0px 10px;
  }
</style>
